package editor;

import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import org.agilelang.generate.UtilFile;
import tab.ViewTab;
import tree.TreePanel;
import tree.TreeProject;

public class Editor extends JFrame {

    public ViewTab tab;
    public PanelSouth panelSouth;
    public String projectLocation = "";
    TreeProject tree;
    TreePanel newContentPane;
    Generate generate;
    private Properties prop_message = new Properties();

    public Editor() {
        this.setIconImage(getImage("editor/images/ml-flame-logo-hi.png"));
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("editor/bundle/MessageBundle_es_PE.properties");
        try {
            prop_message.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MenuToolBar menu_toolbar = new MenuToolBar(this);
        this.setJMenuBar(menu_toolbar.getMenuBar());
        this.getContentPane().add(menu_toolbar.getToolBar(), BorderLayout.NORTH);

        panelSouth = new PanelSouth();
        tab = new ViewTab(this);
        tree = new TreeProject(this);
        generate = new Generate(this);

        newContentPane = new TreePanel(this);

        JSplitPane splitPane = new javax.swing.JSplitPane(javax.swing.JSplitPane.HORIZONTAL_SPLIT, newContentPane/*new JScrollPane(tree.tree)*/, tab);
        splitPane.setOneTouchExpandable(false);
        splitPane.setDividerLocation(220);
        getContentPane().add(splitPane, java.awt.BorderLayout.CENTER);
        addWindowListener(windowListener());
        getContentPane().add(panelSouth, BorderLayout.SOUTH);
    }

    public WindowAdapter windowListener() {
        WindowAdapter action = new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                /*
                 * if (editor.isChange()) { saveDocument(); } 
                 */
                System.exit(0);
            }
        };
        return action;
    }

    public void actionNewProject() {
        DlgNewProject dlg = new DlgNewProject(this, true);
        dlg.setLocationRelativeTo(this);
        dlg.setVisible(true);
        if (dlg.isStatus()) {
            this.panelSouth.setDebug("");
            this.panelSouth.appendDebug(prop_message.getProperty("new_project") +" " + dlg.getName());
            String app_path = dlg.getTxtPath();
            projectLocation = app_path;
            File folder1 = new File(app_path);
            if (!folder1.exists()) {
                folder1.mkdirs();
                File folder2 = new File(app_path);
                folder2.exists();
                this.panelSouth.appendDebug(prop_message.getProperty("creating_directory") + " : " + folder1.getAbsolutePath());
            }
            String[] folders = {"static", "tmpl", "tmp", "config", "source"};
            for (String folder : folders) {
                File folder2 = new File(app_path + File.separator + folder);
                folder2.mkdirs();
                this.panelSouth.appendDebug(prop_message.getProperty("creating_directory") + " : " + app_path + File.separator + folder);
            }

            String[] files = {"/editor/templates/app.config", "/editor/templates/app.agile"};
            String[] files_out = {"config" + File.separator + "app.config", "source" + File.separator + "app.agile"};
            int i = 0;
            for (String file : files) {
                String content = readStream(file);
                createfile(app_path + File.separator + files_out[i], content);
                this.panelSouth.appendDebug(prop_message.getProperty("creating_file") + " : " + app_path + File.separator + files_out[i]);
                i++;
            }

            //tree.setModel(projectLocation);
            newContentPane.setTreeProject(projectLocation);
           
            
            
            this.tab.newProject();
        }
    }

    public void actionOpenProject() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int result = fileChooser.showOpenDialog(this);
        if (result == JFileChooser.CANCEL_OPTION) {
            return;
        }
        this.panelSouth.setDebug("");
        this.panelSouth.appendDebug(prop_message.getProperty("open_project") + " : " + fileChooser.getSelectedFile().getName());
        projectLocation = fileChooser.getSelectedFile().getAbsolutePath();
        //tree.setModel(projectLocation);
        newContentPane.setTreeProject(projectLocation);

        this.tab.openProject();
    }

    public void actionCloseProject() {
        //tree.close();
        newContentPane.clear();
        newContentPane.updateUI();
        this.tab.closeProject();
        projectLocation = "";
    }

    public void actionSave() {
        this.tab.saveAll();
    }

    public void actionGenerate() {
        if (projectLocation.equals("")) {
            this.panelSouth.setDebug("Open Project");
            return;
        }
        this.panelSouth.setDebug("");
        this.tab.saveAll();
        generate.generate(projectLocation);
        this.panelSouth.appendDebug("BUILD SUCCESSFUL");
    }

    public void actionOpenExample(String example) {
        Path currentRelativePath = Paths.get("");
        String s = currentRelativePath.toAbsolutePath().toString();
        System.out.println(s + File.separator + "Example" + File.separator + example);
        projectLocation = System.getProperty("user.dir") + File.separator + example;
        UtilFile.unzip(s + File.separator + "Example" + File.separator + example + ".zip", projectLocation);

        tree.setModel(projectLocation);
        this.tab.newProject();
    }

    //--------------------------------------------------------------------------
    public String readStream(String path) {
        Reader reader = null;
        try {
            InputStream is = this.getClass().getResourceAsStream(path);
            if (is != null) {
                try {
                    reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                } catch (Exception e) {
                    System.out.println(e.toString() + "111111");
                }
            }
        } catch (Exception e) {
            System.out.println(e.toString() + "222222");
        }
        String file = readFileAsString(reader);
        return file;
    }

    protected static String readFileAsString(Reader reader) {
        StringBuffer fileData = new StringBuffer(100000);
        char[] buf = new char[1024];
        int numRead = 0;
        try {
            while ((numRead = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, numRead);
                fileData.append(readData);
                buf = new char[1024];
            }
            reader.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
        return fileData.toString();
    }

    protected void createfile(String Name, String path, String Contenido) {
        Writer output = null;
        System.out.println(path + File.separator + Name);
        File file = new File(path + File.separator + Name);
        try {
            //output = new BufferedWriter(new FileWriter(file));

            output = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file), "UTF8"));

            output.write(Contenido);

            output.flush();
            output.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }

    protected void createfile(String path, String Contenido) {
        Writer output = null;
        System.out.println(path);
        File file = new File(path);
        try {
            output = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file), "UTF8"));

            output.write(Contenido);

            output.flush();
            output.close();
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }

    protected final ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = Editor.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    private Image getImage(String urlimagen) {
        Image retValue = Toolkit.getDefaultToolkit().
                getImage(ClassLoader.getSystemResource(urlimagen));
        return retValue;
    }
}
